package com.gensdai.leliang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.flyco.roundview.RoundTextView;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.OrderInfoProductListAdapter;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.bean.WechatBean;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.dialog.dialog_select_pay_type_test;
import com.gensdai.leliang.entity.parseBean.BaseParse;
import com.gensdai.leliang.entity.parseBean.ParentBean;
import com.gensdai.leliang.popupwindow.BasePopupWindow;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserver;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.gensdai.leliang.view.NoScrollListView;
import com.gensdai.leliang.view.Toaster;
import com.gensdai.leliang.wxapi.WXPayEntryActivity;
import com.gensdai.leliang.zfb.PayResult;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.BuildConfig;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


//订单详情页面
public class OrderInfoActivity extends BaseActivity implements dialog_select_pay_type_test.PayTypeClick {

    public static final String EXTRA_ORDER_ID = "extra_orderid";
    public static final int COMMENT_FINISH = 0x110;
    @BindView(R.id.orderStatus)
    TextView orderStatus;
    //    @BindView(R.id.productIcon)
//    ImageView productIcon;
//    @BindView(R.id.title)
//    TextView title;
//    @BindView(R.id.info)
//    TextView infoText;
//    @BindView(R.id.money)
//    TextView money;
//    @BindView(R.id.count)
//    TextView count;
    @BindView(R.id.nameLable)
    TextView nameLable;
    @BindView(R.id.phoneLable)
    TextView phoneLable;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.shangpingzongjia)
    TextView shangpingzongjia;
    @BindView(R.id.yunfei)
    TextView yunfei;
    @BindView(R.id.dingdanzongjia)
    TextView dingdanzongjia;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.chengzhangbei)
    TextView chengzhangbei;
    @BindView(R.id.shifukuan)
    TextView shifukuan;
    @BindView(R.id.dingdanbianhao)
    TextView dingdanbianhao;
    @BindView(R.id.chuangjianshijian)
    TextView chuangjianshijian;
    @BindView(R.id.fukuanshijian)
    TextView fukuanshijian;
    @BindView(R.id.fahuoshijian)
    TextView fahuoshijian;
    @BindView(R.id.shouhuoshijian)
    TextView shouhuoshijian;
    @BindView(R.id.order_status_hint)
    TextView orderStatusHint;
    @BindView(R.id.fanchengzhangb)
    TextView fanchengzhangb;
    @BindView(R.id.actPayText)
    TextView actPayText;
    @BindView(R.id.productList)
    NoScrollListView productList;

    //付款时间
    @BindView(R.id.paytimeLayout)
    LinearLayout paytimeLayout;
    //发货时间
    @BindView(R.id.sendProductLayout)
    LinearLayout sendProductLayout;
    //收货时间
    @BindView(R.id.shouhuoLayout)
    LinearLayout shouhuoLayout;
    @BindView(R.id.paybtn)
    RoundTextView paybtn;
    @BindView(R.id.logisticBtn)
    RoundTextView logisticBtn;
    @BindView(R.id.confirmOrderBtn)
    RoundTextView confirmOrderBtn;
    @BindView(R.id.outpayBtn)
    RoundTextView outpayBtn;


    dialog_select_pay_type_test test;
    @BindView(R.id.cancelBtn)
    RoundTextView cancelBtn;
    @BindView(R.id.phontbtn)
    TextView phontbtn;
    @BindView(R.id.commentbtn)
    RoundTextView commentbtn;
    private String orderid = "";   //29f6f92bf6da463aa15e670403aab7dc


    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");


    private Upload up;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderid = getIntent().getStringExtra(EXTRA_ORDER_ID);
        ButterKnife.bind(this);

        up = new Upload(this);
        //wxpay begin
        msgApi = WXAPIFactory.createWXAPI(this, AppApplication.APPID, false);
        //动态注册，微信支付会调用广播在当前activity的生命周期內运行
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d("BroadcastReceiver", "BroadcastReceiver");
                if (intent.getAction().equals(WXPayEntryActivity.DETAILORDER)) {
                    //Do Something
                    String payResultType = intent.getStringExtra("type");
                    if (!TextUtils.isEmpty(payResultType)) {
                        //付款成功
                        if (TextUtils.equals(WXPayEntryActivity.CODE_SUCCESS, payResultType)) {
                            if (test != null && test.isShowing())
                                test.dismiss();
                            if (!TextUtils.isEmpty(orderid)) {
                                getOrderInfo(orderid);
                            }
                        } else if (TextUtils.equals(WXPayEntryActivity.CODE_CANCEL, payResultType)) {
                            //取消操作
                        }
                    }
                }
            }
        };
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mLocalBroadcastManager.registerReceiver(mReceiver, new IntentFilter(WXPayEntryActivity.DETAILORDER));
        msgApi.registerApp(AppApplication.APPID);
        //wxpayend
        initview();

        if (!TextUtils.isEmpty(orderid)) {
            getOrderInfo(orderid);
        }

    }

    private void initview() {

    }




    private void getOrderInfo(String orderid) {
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderid);
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().getOrderInfo(params))
                .compose(this.<BaseParse<BaseParse.OrderInfo>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        if (up != null) {
                            up.show();
                        }
                        Log.d("getOrderInfo", "accept");
                    }
                })
                .subscribe(new BaseObserver<BaseParse.OrderInfo>(this) {
                    @Override
                    public void onHandleSuccess(BaseParse.OrderInfo orderInfo) {
                        attrview(orderInfo);
                    }

                    @Override
                    public void onHandleError(int code, String message) {

                        Toaster.showOneToast(code + ":" + message);
                    }

                    @Override
                    public void onRequestEnd() {
                        super.onRequestEnd();
                        if (up != null) {
                            up.dismiss();
                        }
                    }
                });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(requestCode == COMMENT_FINISH){
                commentbtn.setVisibility(View.GONE);
            }
        }
    }

    private void attrview(final BaseParse.OrderInfo info) {

        if (info != null) {
            if (info.orderAttributeMap != null && info.orderAttributeMap.size() > 0) {

                OrderInfoProductListAdapter adapter = new OrderInfoProductListAdapter(this);
                productList.setAdapter(adapter);
                adapter.initAdd(info.orderAttributeMap);

                //评论按钮的点击事件
                commentbtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(OrderInfoActivity.this,PostComment.class);
                        it.putExtra(PostComment.EXTRA_OBJS,(Serializable) info.orderAttributeMap);
                        it.putExtra(PostComment.EXTRA_ID,orderid);
                        startActivityForResult(it,COMMENT_FINISH);
                    }
                });
            }


            shangpingzongjia.setText(getPriceChar(info.proTotalPrice + ""));
            yunfei.setText(getPriceChar(info.transFerFee + ""));
            dingdanzongjia.setText(getPriceChar(info.orderPrice + ""));
            //状态
            orderStatus.setText(getStatusText(info.orderState + ""));
            initStatusOrderView(info);
            //成长贝
            chengzhangbei.setText(getPriceChar(info.grouthBei + ""));
            //实际付款
            shifukuan.setText(getPriceChar(info.waitPayPrice+""));
            if (info != null && info.address != null && info.address.name != null)
                nameLable.setText("收货人:" + info.address.name);
            if (info != null && info.address != null && info.address.phone != null)
                phoneLable.setText(info.address.phone);
            if (info != null && info.address != null && info.address.address != null)
                address.setText("收货地址:" + info.address.provinceId + info.address.cityId + info.address.address);

            fanchengzhangb.setText(getPriceChar(info.backGrouthBey + ""));
            //订单编号
            dingdanbianhao.setText(info.orderNo);

            if (info.orderCreateTime != null) {
                Date d = new Date(info.orderCreateTime.time);
                chuangjianshijian.setText(sdf.format(d));
            }

            orderStatusHint.setText(info.invalidTimeNote);


            paybtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    test = new dialog_select_pay_type_test(OrderInfoActivity.this, getSupportFragmentManager());
                    test.setOrderID(orderid);
                    test.setPrice(info.waitPayPrice);
                    test.setOnPayTypeClick(OrderInfoActivity.this);    //调用付款回调
                    test.setOnKeyBordCallBackListener(keybordListener);
                    test.showPopupWindow();
                    test.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {

                        }
                    });
                }
            });
            cancelBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    postOrderCancel(orderid);
                }
            });
            //拨打电话
            phontbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent intent1 = new Intent(Intent.ACTION_DIAL);
                    intent1.setData(Uri.parse("tel:400-920-3600"));
                    startActivity(intent1);
                }
            });

        }


        //置顶
        orderStatus.setFocusable(true);
        orderStatus.setFocusableInTouchMode(true);
        orderStatus.requestFocus();
    }


    dialog_select_pay_type_test.KeybordListener keybordListener = new dialog_select_pay_type_test.KeybordListener() {

        @Override
        public void onInputCompleted(CharSequence password) {
        }

        @Override
        public void onInputCompleted(CharSequence password, String ordereid) {
            postBanlancePay(password.toString());
        }

        @Override
        public void onForgetPassword() {

        }

        @Override
        public void onPasswordCorrectly() {
            test.dismiss();
            if (!TextUtils.isEmpty(orderid)) {
                getOrderInfo(orderid);
            }
        }

        @Override
        public void onCancel() {
        }

    };


    private void initStatusOrderView(BaseParse.OrderInfo of) {

        cancelBtn.setVisibility(View.GONE);
        paybtn.setVisibility(View.GONE);
        logisticBtn.setVisibility(View.GONE);
        confirmOrderBtn.setVisibility(View.GONE);
        commentbtn.setVisibility(View.GONE);
        outpayBtn.setVisibility(View.GONE);

        outpayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(OrderInfoActivity.this,ApplyRefund.class);
                it.putExtra(ApplyRefund.EXTRA_ORDERID,orderid);
                startActivity(it);
            }
        });

        switch (of.orderState) {
            case 1:
                //未付款 显示文字是应付款  显示取消订单跟付款的layout
                actPayText.setText(getString(R.string.act_Pay_1));
                paytimeLayout.setVisibility(View.GONE);
                sendProductLayout.setVisibility(View.GONE);
                shouhuoLayout.setVisibility(View.GONE);
                //未付款显示取消订单跟付款按钮
                cancelBtn.setVisibility(View.VISIBLE);
                paybtn.setVisibility(View.VISIBLE);
                break;
            case 2:

                actPayText.setText(getString(R.string.act_Pay));
                paytimeLayout.setVisibility(View.VISIBLE);
                sendProductLayout.setVisibility(View.GONE);
                shouhuoLayout.setVisibility(View.GONE);

                if (of.orderPayTime != null) {
                    Date d = new Date(of.orderPayTime.time);
                    fukuanshijian.setText(sdf.format(d));
                }

                outpayBtn.setVisibility(View.VISIBLE);
                //买家已付款                  退款（没有退款时不显示按钮）  0:不可退货 1:可以退货
                if(TextUtils.equals("1",of.type)){
                    outpayBtn.setVisibility(View.VISIBLE);
                }else{
                    outpayBtn.setVisibility(View.GONE);
                }

                break;
            case 3:
                actPayText.setText(getString(R.string.act_Pay));
                paytimeLayout.setVisibility(View.VISIBLE);
                sendProductLayout.setVisibility(View.VISIBLE);
                shouhuoLayout.setVisibility(View.VISIBLE);

                if (of.orderPayTime != null) {
                    Date f = new Date(of.orderPayTime.time);
                    fukuanshijian.setText(sdf.format(f));
                }
                if (of.deliverDate != null) {
                    Date f = new Date(of.deliverDate.time);
                    fahuoshijian.setText(sdf.format(f));
                }
                //已经发货
                logisticBtn.setVisibility(View.VISIBLE);
                confirmOrderBtn.setVisibility(View.VISIBLE);
                logisticBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(OrderInfoActivity.this, LogisticsInfoActivity.class);
                        it.putExtra("orderid", orderid);
                        startActivity(it);
                    }
                });
                confirmOrderBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        AlertDialog alertDialog;
                        final AlertDialog.Builder normalDialog =
                                new AlertDialog.Builder(OrderInfoActivity.this);
                        normalDialog.setMessage("请收到货后确认收货哦！");
                        normalDialog.setPositiveButton("确认收货", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ConfirmReceipt(orderid);
                                dialog.dismiss();
                            }
                        });
                        normalDialog.setNegativeButton("点错了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                        normalDialog.setCancelable(false);
                        // 显示
                        alertDialog = normalDialog.create();
                        alertDialog.show();
                    }
                });
                break;
            case 4:
                if (of.receiptDate != null) {
                    Date f = new Date(of.receiptDate.time);
                    shouhuoshijian.setText(sdf.format(f));
                }
                logisticBtn.setVisibility(View.VISIBLE);
                if(!of.hasEvaluate){
                    commentbtn.setVisibility(View.VISIBLE);
                }

                //已经发货
                logisticBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(OrderInfoActivity.this, LogisticsInfoActivity.class);
                        it.putExtra("orderid", orderid);
                        startActivity(it);
                    }
                });
                break;
            case 7:
                //退款完成
                outpayBtn.setVisibility(View.VISIBLE);
                outpayBtn.setText("退款完成");
                outpayBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(OrderInfoActivity.this,ActivityApplyResultInfo.class);
                        it.putExtra(ActivityApplyResultInfo.EXTRA_ORDERID,orderid);
                        startActivity(it);
                    }
                });
                break;
            case 8:
                //退款中
                outpayBtn.setVisibility(View.VISIBLE);
                outpayBtn.setText("退款中");
                outpayBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent it = new Intent(OrderInfoActivity.this,ActivityApplyResultInfo.class);
                        it.putExtra(ActivityApplyResultInfo.EXTRA_ORDERID,orderid);
                        startActivity(it);
                    }
                });
                break;
            default:
                break;
        }
    }

    private void postBanlancePay(String pay) {
        String userid = PreferencesUtils.getStringPreference(this, OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //获取用户id没有登陆就是没有

        Map<String, String> params = new HashMap<>();
        params.put("userId", userid);   //手机号
        params.put("orderId", orderid);
        params.put("payPassword", BaseUtils.EncryptedPassword(pay));

//        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().payBalance(params))
//                .compose(this.<ParentBean>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
//                .doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(@NonNull Disposable disposable) throws Exception {
//                        //开始监听前的处理，一般用于显示dialog什么的
//////                        if (hud != null) {
//////                            hud.show();
//////                        }
//
//                        Log.d("accept", "accept");
//                    }
//                }).subscribe(new Observer<ParentBean>() {
//            @Override
//            public void onSubscribe(@NonNull Disposable d) {
//                //可以取消订阅
//                //还可以判断是否处于取消状态
//                //boolean b=d.isDisposed();
//                Log.d("onSubscribe", "onSubscribe");
//            }
//
//            @Override
//            public void onNext(@NonNull ParentBean s) {
//                //处理得到的数据
//                Toast.makeText(OrderInfoActivity.this, s.getMessage(), Toast.LENGTH_SHORT).show();
//
//                if (s.isSuccess()) {
//                    test.setkeyPadStatus(true);
//                } else {
//                    test.setkeyPadStatus(false, s.getMessage());
//                }
//                Log.e("quick_login", s.getMessage());
//            }
//
//            @Override
//            public void onError(@NonNull Throwable e) {
//                //异常处理
//                test.setkeyPadStatus(false, "出现了一个问题");
////                        Log.e("onError", e.getMessage());
//            }
//
//            @Override
//            public void onComplete() {
//                //监听完毕后的处理
//                Log.d("onComplete", "onComplete");
//            }
//        });

        ApiService.getInstance(this).payBalance(params)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<ParentBean>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ParentBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull ParentBean s) {
                        //处理得到的数据
                        Toast.makeText(OrderInfoActivity.this, s.getMessage(), Toast.LENGTH_SHORT).show();

                        if (s.isSuccess()) {
                            test.setkeyPadStatus(true);
                        } else {
                            test.setkeyPadStatus(false, s.getMessage());
                        }
                        Log.e("quick_login", s.getMessage());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        test.setkeyPadStatus(false, "出现了一个问题");
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    private void postOrderCancel(final String orderid) {
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderid);

        ApiService.getInstance(this).postOrderCancel(params)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<BaseParse>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseParse>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull BaseParse s) {
                        //处理得到的数据
                        Toast.makeText(OrderInfoActivity.this, s.message, Toast.LENGTH_SHORT).show();
                        if (s.success) {
                            //如果取消成功刷新当前页面
                            OrderInfoActivity.this.finish();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        e.printStackTrace();
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");

                        if (up != null && up.isShowing()) {
                            up.dismiss();
                        }
                    }
                });

    }

    /*1:待付款，2：待发货 3：已发货(待收货)：4：已完成  5:已取消
    */
    public static String getStatusText(String statusCode) {
        String codetext = "";

        switch (statusCode) {
            case "1":
                codetext = "买家未付款";
                break;
            case "2":
                codetext = "买家已付款";
                break;
            case "3":
                codetext = "卖家已发货";
                break;
            case "4":
                codetext = "交易成功";
                break;
            case "5":
                codetext = "已取消";
                break;
            case "7":
                codetext = "已退款";
                break;
            case "8":
                codetext = "退款中";
                break;
            default:
                codetext = "未定义";
                break;
        }

        return codetext;
    }

    public static String getPriceChar(String price) {
        String priceChar = "¥";
        priceChar = String.format(AppApplication.getContext().getString(R.string.product_price).toString(), price);
        return priceChar;
    }


    /*获取Alipay的支付 URL*/
    @Override
    public void PayAli(String orderid) {
        String userid = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //
        String userno = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userno, ""); //

        Map<String, String> params = new HashMap<>();
        params.put("userno", userno);
        params.put("userId", userid);
        params.put("orderId", orderid);

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().createAliPay(params))
                .compose(this.<BaseParse<BaseParse.properOrder>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(
                        new Observer<BaseParse<BaseParse.properOrder>>() {
                            @Override
                            public void onSubscribe(@NonNull Disposable d) {
                                //可以取消订阅
                                //还可以判断是否处于取消状态
                                //boolean b=d.isDisposed();

                                Log.d("onSubscribe", "onSubscribe");
                            }

                            @Override
                            public void onNext(@NonNull BaseParse<BaseParse.properOrder> s) {
                                //处理得到的数据
                                if (BuildConfig.DEBUG) {
                                    Toast.makeText(OrderInfoActivity.this, s.message, Toast.LENGTH_SHORT).show();
                                }
                                if (s.data != null && s.data.payAliUrl != null) {
                                    startPayAli(s.data.payAliUrl);
                                } else {
                                    if (BuildConfig.DEBUG) {
                                        Toaster.showOneToast("订单详情获取服务器aliUrl失败，该窗口只会在开发模式中显示");
                                    }
                                }
                                Log.e("quick_login", s.message);

                                if (up != null) {
                                    up.dismiss();
                                }
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                //异常处理
                                e.printStackTrace();
                                if (up != null) {
                                    up.dismiss();
                                }
                            }

                            @Override
                            public void onComplete() {
                                //监听完毕后的处理
                                Log.d("onComplete", "onComplete");
                                if (up != null) {
                                    up.dismiss();
                                }
                            }
                        }
                );
    }


    private void startPayAli(final String url) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderInfoActivity.this);
                Map<String, String> result = alipay.payV2(url, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(
                            (Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    Log.e("my_wallet", "resultInfo:" + resultInfo);
                    Log.e("my_wallet", "resultStatus:" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(OrderInfoActivity.this, "付款成功",
                                Toast.LENGTH_SHORT).show();
                        //同步回调服务器
//                        returnPayUrl(resultInfo);
                        if (test != null && test.isShowing())
                            test.dismiss();
                        if (!TextUtils.isEmpty(orderid)) {
                            getOrderInfo(orderid);
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(OrderInfoActivity.this, "付款失败",
                                Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    up.dismiss();
                    break;
            }
        }

        ;
    };


    /**
     * 确认收货
     *
     * @param orderid
     */
    private void ConfirmReceipt(final String orderid) {
        Map<String, String> params = new HashMap<>();
        params.put("orderId", orderid);
        params.put("tokenId", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        params.put("userId", getSharedPreferences("User", MODE_PRIVATE).getString("user_id", ""));
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().ConfirmReceiptBean(params))
                //涉及到IO操作
                .compose(this.<BaseParse<String>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new Observer<BaseParse<String>>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();
                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull BaseParse<String> s) {
                        if (s.success) {
                            //如果成功刷新当前页面
                            getOrderInfo(orderid);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        e.printStackTrace();
//                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");

                        if (up != null && up.isShowing()) {
                            up.dismiss();
                        }
                    }
                });

    }


    public static IWXAPI msgApi;

    //检查微信是否安装
    public boolean isWXAppInstalled() {
        return msgApi.isWXAppInstalled();
    }

    @Override
    public void PayWechat(final String orderID) {

        if (!isWXAppInstalled()) {
            Toaster.showOneToast("没有检测到安装微信客户端，请更换支付方式");
            return;
        }


        String userid = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreper3Activity.prefreceName, OrderPreper3Activity.prefrece_userid, ""); //
        String userno = PreferencesUtils.getStringPreference(AppApplication.getContext(), OrderPreper3Activity.prefreceName, OrderPreper3Activity.prefrece_userno, ""); //

        Map<String, String> params = new HashMap<>();
        params.put("userno", userno);
        params.put("userId", userid);
        params.put("orderId", orderid);
        params.put("clientType", AppApplication.ClientType);

        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().CreateWechatPay(params))
                .compose(this.<BaseParse<WechatBean>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        if (up != null) {
                            up.show();
                        }
                        Log.d("accept", "accept");
                    }
                })
                .subscribe(new BaseObserver<WechatBean>(OrderInfoActivity.this) {
                               @Override
                               public void onHandleSuccess(WechatBean properOrder) {
                                   //处理得到的数据

                                   if (properOrder != null) {
                                       //变换为wechat的对象开始调用微信支付
                                       PayReq request = new PayReq();

                                       request.appId = properOrder.appid;

                                       request.partnerId = properOrder.partnerid;

                                       request.prepayId = properOrder.prepayid;

                                       request.packageValue = properOrder.packages;

                                       request.nonceStr = properOrder.noncestr;

                                       request.timeStamp = properOrder.timestamp;

                                       request.sign = properOrder.sign;
                                       request.extData = WXPayEntryActivity.DETAILORDER + "#" + orderID;

                                       msgApi.sendReq(request);
                                   } else {
                                       if (BuildConfig.DEBUG) {
                                           Toaster.showOneToast("获取服务器wechatUrl失败，该窗口只会在开发模式中显示");
                                       }
                                   }

                                   if (up != null) {
                                       up.dismiss();
                                   }
                               }

                               @Override
                               public void onHandleError(int code, String message) {
                                   if (BuildConfig.DEBUG) {
                                       Toast.makeText(OrderInfoActivity.this, message, Toast.LENGTH_SHORT).show();
                                   }
                               }

                               @Override
                               public void onRequestEnd() {
                                   super.onRequestEnd();
                                   if (up != null) {
                                       up.dismiss();
                                   }
                               }

                               @Override
                               public void onFailure(Throwable e) {
                                   super.onFailure(e);
                                   if (up != null) {
                                       up.dismiss();
                                   }
                               }
                           }
                );
    }

    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mReceiver;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mReceiver);
    }


    @Override
    protected String getTitleStr() {
        return "订单详情";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_order_info;
    }
}
